package com.hpin.fansea.home;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hpin.fansea.R;
import com.hpin.fansea.base.BaseActivity;
import com.hpin.fansea.bean.LoadPicResult;
import com.hpin.fansea.bean.Maintain;
import com.hpin.fansea.bean.ResultBaseBean;
import com.hpin.fansea.choosepic.MyAdapter;
import com.hpin.fansea.utils.CommonUtils;
import com.hpin.fansea.utils.Constant;
import com.hpin.fansea.utils.HttpUtil;
import com.hpin.fansea.widget.ActionSheetDialog;
import com.lidroid.xutils.http.RequestParams;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 物业报修
 * Created by Aaron on 15/9/8.
 */
public class RepairActivity extends BaseActivity {

    private List<String> picUrls = new ArrayList<String>();// 存放用户上传的图片的地址

    private ExecutorService executor;

    /*相册选择的code*/
    private static final int PHOTO_ALBUM_CODE = 101;
    /*拍照的code*/
    private static final int TAKE_PHOTO_CODE = 102;

    /*拍照的文件保存的位置*/
    private File currentFile;

    private Button pay_repair_btn;

    private EditText repair_contacts;
    private EditText repair_phone;
    private EditText repair_reason;

    private TextView repair_address;

    private LinearLayout repair_llPhone;

    private TextView repair_tvPhone;
    private ImageView iv_first;
    private ImageView iv_second;
    private ImageView iv_third;
    private ImageView iv_four;
    private ArrayList<String> tempTakeLists;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_repair);

        tempTakeLists = new ArrayList<String>();

        initView();

        setUserData();

    }

    private void initView() {

        // 联系人
        repair_contacts = (EditText) findViewById(R.id.repair_contacts);
        // 地址
        repair_address = (TextView) findViewById(R.id.repair_address);
        // 打电话布局
        repair_llPhone = (LinearLayout) findViewById(R.id.repair_llPhone);
        // 报修电话
        repair_tvPhone = (TextView) findViewById(R.id.repair_tvPhone);
        // 电话号码
        repair_phone = (EditText) findViewById(R.id.repair_etPhone);
        // 原因
        repair_reason = (EditText) findViewById(R.id.repair_reason);
        // 报修button
        pay_repair_btn = (Button) findViewById(R.id.pay_repair_btn);

        ImageView iv_left = (ImageView) findViewById(R.id.iv_left);
        TextView tv_title = (TextView) findViewById(R.id.tv_title);

        tv_title.setText(getResources().getString(R.string.property_repair));

        repair_llPhone.setOnClickListener(this);
        pay_repair_btn.setOnClickListener(this);
        iv_left.setOnClickListener(this);

        iv_first = (ImageView) findViewById(R.id.iv_first);
        iv_second = (ImageView) findViewById(R.id.iv_second);
        iv_third = (ImageView) findViewById(R.id.iv_third);
        iv_four = (ImageView) findViewById(R.id.iv_four);

        iv_first.setOnClickListener(this);
        iv_second.setOnClickListener(this);
        iv_third.setOnClickListener(this);
        iv_four.setOnClickListener(this);

        setClickableFalse(iv_second);
        setClickableFalse(iv_third);
        setClickableFalse(iv_four);

    }

    /**
     * 设置用户的基本数据
     */
    private void setUserData() {

        repair_address.setText(sp.getString(Constant.communityId, "") + "期" + sp.getString(Constant.buildingNo, "")
                + sp.getString(Constant.unitNo, "") + sp.getString(Constant.houseNo, ""));

        repair_contacts.setText(sp.getString(Constant.userName, ""));

        repair_phone.setText(sp.getString(Constant.mobile, ""));

    }

    protected void checkout() {
        // 报修理由为空
        if (TextUtils.isEmpty(repair_reason.getText().toString())) {
            showToast("报修原因不能为空");
            return;
        }
        // 报修原因应在4-20个字
        if (repair_reason.getText().toString().length() < 4
                || repair_reason.getText().toString().length() > 20) {
            showToast("报修原因应在4-20个字");
            return;
        }
        // 手机号不能为空
        if (TextUtils.isEmpty(repair_phone.getText().toString())) {
            showToast("手机号不能为空");
            return;
        }
        // 手机号格式不正确
        if (!CommonUtils.isPhone(repair_phone.getText().toString())) {
            showToast("手机号格式不正确");
            return;
        }
        // 联系人不能为空
        if (TextUtils.isEmpty(repair_contacts.getText().toString())) {
            showToast("联系人不能为空");
            return;
        }
        // 联系人不能为空
        if (repair_contacts.getText().toString().length() < 2
                || repair_contacts.getText().toString().length() > 4) {
            showToast("联系人不能为空");
            return;
        }

        if (CommonUtils.isNull(sp.getString(Constant.houseId, ""))) {
            showToast("未认证用户");
            return;
        }

        submit2Repair();

    }

    /**
     * 提交物业报修
     */
    private void submit2Repair() {

        Maintain json = new Maintain();
        json.maintenanceUserid = repair_contacts.getText().toString().trim();
        json.phoneNum = repair_phone.getText().toString().trim();
        json.maintenanceCont = repair_reason.getText().toString().trim();

        if (picUrls.size() > 0) {
            StringBuilder sb = new StringBuilder();
            for (String picUrl : picUrls) {
                sb.append(picUrl + Constant.PHOTOS_SUB);
            }
            String strHole = sb.toString();

            json.photo = strHole;
        } else {
            json.photo = "";
        }
        String maintain = JSON.toJSONString(json);

        RequestParams params = new RequestParams();
        params.addBodyParameter("maintain", maintain);
        params.addBodyParameter("token", sp.getString(Constant.token, ""));
        params.addBodyParameter("systemType", Constant.SYSTEM_TYPE);

        HttpUtil.getInstance().setPostRequest("提交中...", this, Constant.WEB_ROOT + Constant.ADDMAINTAIN + sp.getString(Constant.houseId, ""),
                params, new HttpUtil.SuccessListener() {
                    @Override
                    public void setOnSuccessListener(String str) {

                        try {

                            ResultBaseBean resultBaseBean = JSONObject.parseObject(str, ResultBaseBean.class);

                            if (Constant.STATUS_SUCESS.equals(resultBaseBean.status)) {
                                //提交成功
                                showToast("提交成功");
                                finish();

                            } else {
                                showToast(resultBaseBean.message);
                            }

                        } catch (Exception e) {

                            e.printStackTrace();
                            showToast("提交失败");

                        }

                    }
                }, null);

    }

    @Override
    public void widgetClick(View v) {
        switch (v.getId()) {
            case R.id.iv_left://返回

                finish();

                break;
            case R.id.pay_repair_btn://报修

                checkout();

                break;

            case R.id.repair_llPhone: // 打电话

                // 提示对话框
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("提示");
                builder.setMessage("是否要拨打电话");
                builder.setPositiveButton("确定",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface arg0, int arg1) {
                                String phoneNum = repair_tvPhone.getText().toString().trim();
                                if (!TextUtils.isEmpty(phoneNum)) {
                                    Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + phoneNum));
                                    startActivity(intent);
                                } else {
                                    showToast("未获取到手机号码");
                                }
                            }
                        });
                builder.setNegativeButton("取消", null);
                builder.show();

                break;

            case R.id.iv_first:
            case R.id.iv_second:
            case R.id.iv_third:
            case R.id.iv_four:

                showChoose();

                break;

            default:
                break;
        }
    }

    /**
     * 弹出选择照片的对话框
     */
    protected void showChoose() {

        new ActionSheetDialog(this)
                .builder()
                .setCancelable(true)
                .setCanceledOnTouchOutside(true)
                .addSheetItem("拍照", ActionSheetDialog.SheetItemColor.Blue,
                        new ActionSheetDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                // 拍照
                                getTakePhoto();

                            }

                        })
                .addSheetItem("去相册选择", ActionSheetDialog.SheetItemColor.Blue,
                        new ActionSheetDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                // 从相册中选择
                                getFromPhotoAlbum();
                            }
                        }).show();

    }

    /**
     * 从相册中选择
     */
    private void getFromPhotoAlbum() {

        Intent intent = new Intent(this, ChoosePhotoActivity.class);
        startActivityForResult(intent, PHOTO_ALBUM_CODE);

    }

    /**
     * 拍照
     */
    private void getTakePhoto() {

        String cacheDir = Environment.getExternalStorageDirectory().getPath() + Constant.PHOTO_CACHE;
        File photoFile = new File(cacheDir);
        //文件夹不存在就创建文件夹
        if (!photoFile.exists()) {
            photoFile.mkdirs();
        }
        //创建存放图片的jpg文件
        currentFile = new File(photoFile, System.currentTimeMillis() + ".jpg");

        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(currentFile));
        startActivityForResult(intent, TAKE_PHOTO_CODE);
    }

    /**
     * 让控件不可点击
     *
     * @param iv
     */
    private void setClickableFalse(ImageView iv) {

        iv.setClickable(false);
        iv.setFocusable(false);
        iv.setEnabled(false);

    }

    /**
     * 让控件可点击
     *
     * @param iv
     */
    private void setClickableTrue(ImageView iv) {

        iv.setClickable(true);
        iv.setFocusable(true);
        iv.setEnabled(true);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == PHOTO_ALBUM_CODE) {//从相册中选择

            if (data == null)
                return;

            ArrayList<String> selectPics = data.getStringArrayListExtra("selectedPhotos");

            tempTakeLists.addAll(selectPics);

            //逐张上传图片
            for (String pic : selectPics) {

                loadPicToNet(pic);

            }

           setImage(selectPics);

        } else  if (requestCode == TAKE_PHOTO_CODE) {

            //上传图片
            if (currentFile != null && currentFile.exists()) {

                loadPicToNet(currentFile.getPath());

            }

            tempTakeLists.add(currentFile.getPath());
            setImage(tempTakeLists);

        }

    }

    private void setImage(List<String> selectPics) {

        switch (selectPics.size()) {

            case 1:

                setClickableFalse(iv_first);
                setClickableTrue(iv_second);

                setClickableFalse(iv_third);
                setClickableFalse(iv_four);
                iv_second.setImageResource(R.mipmap.icon_choose_pic);

                iv_third.setImageResource(R.mipmap.icon_wait_choose);
                iv_four.setImageResource(R.mipmap.icon_wait_choose);

                iv_first.setImageBitmap(CommonUtils.getBitmapFromPath(selectPics.get(0)));

                break;
            case 2:

                setClickableFalse(iv_first);
                setClickableFalse(iv_second);
                setClickableTrue(iv_third);

                setClickableFalse(iv_four);
                iv_third.setImageResource(R.mipmap.icon_choose_pic);

                iv_four.setImageResource(R.mipmap.icon_wait_choose);

                iv_first.setImageBitmap(CommonUtils.getBitmapFromPath(selectPics.get(0)));
                iv_second.setImageBitmap(CommonUtils.getBitmapFromPath(selectPics.get(1)));

                break;
            case 3:

                setClickableFalse(iv_first);
                setClickableFalse(iv_second);
                setClickableFalse(iv_third);
                setClickableTrue(iv_four);
                iv_four.setImageResource(R.mipmap.icon_choose_pic);

                iv_first.setImageBitmap(CommonUtils.getBitmapFromPath(selectPics.get(0)));
                iv_second.setImageBitmap(CommonUtils.getBitmapFromPath(selectPics.get(1)));
                iv_third.setImageBitmap(CommonUtils.getBitmapFromPath(selectPics.get(2)));

                break;
            case 4:

                setClickableFalse(iv_first);
                setClickableFalse(iv_second);
                setClickableFalse(iv_third);
                setClickableFalse(iv_four);

                iv_first.setImageBitmap(CommonUtils.getBitmapFromPath(selectPics.get(0)));
                iv_second.setImageBitmap(CommonUtils.getBitmapFromPath(selectPics.get(1)));
                iv_four.setImageBitmap(CommonUtils.getBitmapFromPath(selectPics.get(3)));

                break;

        }

    }


    /**
     * 上传图片
     *
     * @param picturePath 该图片在手机上的地址
     */
    private void loadPicToNet(String picturePath) {

        if (executor == null)
            executor = Executors.newSingleThreadExecutor();

        executor.execute(loadToNet(CommonUtils.compressByte(CommonUtils.getBitmapFromPath(picturePath))));

    }

    /**
     * 上传图片的runnable
     *
     * @param bytes 图片的字节数组
     * @return
     */
    private Runnable loadToNet(final byte[] bytes) {

        return new Thread() {
            @Override
            public void run() {

                String upResult = HttpUtil.getInstance().load(Constant.WEB_ROOT + Constant.UPLOADPIC + "/" + sp.getString(Constant.token, ""), bytes);

                try {

                    LoadPicResult loadPicResult = JSONObject.parseObject(upResult, LoadPicResult.class);

                    if (Constant.STATUS_SUCESS.equals(loadPicResult.status)) {

                        //上传成功,保存到上传的集合中
                        picUrls.add(loadPicResult.result);

                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        };
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        //删除集合中的图片
        MyAdapter.mSelectedImage.clear();

    }
}
